package com.yiqi.liebang.feature.home.view;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.suozhang.framework.component.recyclerview.DividerItemDecoration;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.widget.EmptyView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.rongim.bean.ShareQuestionBean;
import com.yiqi.liebang.common.rongim.msg.QuestionMessage;
import com.yiqi.liebang.common.widget.RatingBar;
import com.yiqi.liebang.common.widget.ShareBottomDialog;
import com.yiqi.liebang.common.widget.dialog.BaseAnimatorSet;
import com.yiqi.liebang.common.widget.dialog.BounceTopEnter;
import com.yiqi.liebang.entity.bo.OrderQuestionInfofBo;
import com.yiqi.liebang.entity.bo.QuestionDetailBo;
import com.yiqi.liebang.entity.enums.OrderType;
import com.yiqi.liebang.feature.home.view.adapter.QuestionRecommendAdapter;
import com.yiqi.liebang.feature.mine.view.UserInfoActivity;
import com.yiqi.liebang.feature.order.contract.QuestionInfoContract;
import com.yiqi.liebang.feature.order.dependencies.questionInfo.DaggerQuestionInfoComponent;
import com.yiqi.liebang.feature.order.dependencies.questionInfo.QuestionInfoPresenterModule;
import com.yiqi.liebang.feature.people.view.FriendsListActivity;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import cn.rongcloud.contactcard.Friend;
import io.rong.imkit.RongIM;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;

public class AskDetailActivity extends BaseActivity implements QuestionInfoContract.View, Toolbar.OnMenuItemClickListener,
        RadioGroup.OnCheckedChangeListener, BaseQuickAdapter.OnItemClickListener, View.OnClickListener {
    @Inject
    QuestionInfoContract.Presenter mPresenter;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tv_ask_info_sign)
    TextView mTvAskInfoSign;
    @BindView(R.id.tv_question_info_content)
    TextView mTvQuestionInfoContent;
    @BindView(R.id.iv_question_info_head)
    ImageView mIvQuestionInfoHead;
    @BindView(R.id.tv_order_question_name)
    TextView mTvOrderQuestionName;
    @BindView(R.id.iv_question_info_position)
    TextView mIvQuestionInfoPosition;
    @BindView(R.id.iv_user_position)
    ImageView mIvUserPosition;
    @BindView(R.id.iv_question_info_help)
    TextView mIvQuestionInfoHelp;
    @BindView(R.id.star_question_info)
    RatingBar mStarQuestionInfo;
    @BindView(R.id.btn_question_info_ask)
    TextView mBtnQuestionInfoAsk;
    @BindView(R.id.tv_question_info_shixiao)
    TextView mTvQuestionInfoShixiao;
    @BindView(R.id.type_question_had_pay)
    LinearLayout mTypeQuestionHadPay;
    @BindView(R.id.type_question_had_expired)
    LinearLayout mTypeQuestionHadExpired;
    @BindView(R.id.type_question_had_fefused)
    LinearLayout mTypeQuestionHadFefused;
    @BindView(R.id.tv_question_expert_shixiao)
    TextView mTvQuestionExpertShixiao;
    @BindView(R.id.type_question_validate_expert)
    LinearLayout mTypeQuestionValidateExpert;
    @BindView(R.id.view_expert_info)
    LinearLayout mViewExpertInfo;
    @BindView(R.id.btn_user_register)
    TextView mBtnUserRegister;
    @BindView(R.id.rgp_topic_type)
    RadioGroup mRgpTopicType;
    @BindView(R.id.edt_answer_content)
    EditText mEdtAnswerContent;
    @BindView(R.id.type_question_answer_expert)
    LinearLayout mTypeQuestionAnswerExpert;
    @BindView(R.id.type_question_ignore_expert)
    LinearLayout mTypeQuestionIgnoreExpert;
    @BindView(R.id.tv_answer_content)
    TextView mTvAnswerContent;
    @BindView(R.id.type_question_reply_expert)
    RelativeLayout mTypeQuestionReplyExpert;
    @BindView(R.id.view_question_info)
    LinearLayout mViewQuestionInfo;
    @BindView(R.id.tv_answer_content_comment)
    TextView mTvAnswerContentComment;
    @BindView(R.id.type_question_had_reply)
    RelativeLayout mTypeQuestionHadReply;
    @BindView(R.id.rb_queestion_comment_star)
    RatingBar mRbQueestionCommentStar;
    @BindView(R.id.tv_show_star)
    TextView mTvShowStar;
    @BindView(R.id.btn_confrim_comment)
    TextView mBtnConfrimComment;
    @BindView(R.id.rb_user_question_star)
    RatingBar mRbUserQuestionStar;
    @BindView(R.id.view_to_comment)
    LinearLayout mViewToComment;
    @BindView(R.id.iv_user_certification)
    ImageView mIvUserCertification;
    @BindView(R.id.rv_question_recommend)
    RecyclerView mRvQuestioRecommend;
    @BindView(R.id.iv_show_LOOK)
    TextView mIvShowLOOK;
    @BindView(R.id.iv_look_one)
    ImageView mIvLookOne;
    @BindView(R.id.tv_show_count)
    TextView mTvShowCount;
    @BindView(R.id.view_count)
    LinearLayout mViewCount;
    @BindView(R.id.rgb_answer_1look)
    RadioButton mRgbAnswer1look;
    @BindView(R.id.rgb_answer_free)
    RadioButton mRgbAnswerFree;
    @BindView(R.id.btn_confrim_answer)
    TextView mBtnConfrimAnswer;
    @BindView(R.id.btn_zhankai_all)
    TextView mBtnZhankaiAll;
    Boolean flag = true;


    private int mAnswerType = 1;
    UMImage image;//网络图片
    UMWeb umWeb;
    ShareBottomDialog mShareDialog;

    private float mScore;
    private String mAnswerId;
    private boolean isExpert = false;
    private QuestionRecommendAdapter mAdapter;
    private EmptyView mEmptyView;
    QuestionDetailBo mData;

    private boolean isPay = false;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_ask_detail;
    }

    @Override
    protected void initInjector() {
        DaggerQuestionInfoComponent.builder().questionInfoPresenterModule(new QuestionInfoPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {

        initAdapter();
        isExpert = this.getIntent().getBooleanExtra("is_expert", false);
        mToolbar.inflateMenu(R.menu.menu_share);
        mToolbar.setOnMenuItemClickListener(this);
        initToolBar(mToolbar, "问答详情", true, true);
        mShareDialog = new ShareBottomDialog(this, null, false);
    }

    @Override
    protected void initData() {
        mAnswerId = this.getIntent().getStringExtra("answer_id");
        mPresenter.getOrderQuestionDetail(mAnswerId);

    }

    @Override
    protected void initEvent() {
        mRgpTopicType.setOnCheckedChangeListener(this);
    }

    @Override
    public void showOrderQuestionInfoSuccess(OrderQuestionInfofBo data) {


    }

    @Override
    public void showOrderQuestionDetailSuccess(QuestionDetailBo data) {
        mData = data;
        mTvShowCount.setText(data.getViewNum() + "人查看");
        mViewCount.removeAllViews();
        for (int i = 0; i < data.getViewUser().size(); i++) {
            ImageView imageView = new ImageView(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(98, 98);
            layoutParams.setMargins(15, 0, 0, 0);
            imageView.setLayoutParams(layoutParams);
            AM.image().bindToCircleObject(data.getViewUser().get(i).getUserHead(), imageView);
            mViewCount.addView(imageView);
        }


        AM.image().bindToCircleObject(data.getUserAccountFormMap().getUserHead(), mIvQuestionInfoHead);
//        mTvQuestionInfoContent.setText(data.getQuizcontent());
        mTvOrderQuestionName.setText(data.getUserAccountFormMap().getUserName());
        mIvQuestionInfoPosition.setText(data.getUserAccountFormMap().getPosition());
        mIvQuestionInfoHelp.setText("帮助过" + data.getUserAccountFormMap().getHelpNum() + "人");
        mIvUserCertification.setVisibility(data.getUserAccountFormMap().getIsBasic()==1?View.VISIBLE:View.GONE);
        mIvUserPosition.setVisibility(data.getUserAccountFormMap().getIsOccupation()==1?View.VISIBLE:View.GONE);
        mTvAnswerContentComment.setText(data.getAnswerContent());
        mStarQuestionInfo.setStar(data.getStartLevel());
        mRbUserQuestionStar.setStar(data.getStartLevel());

        mTvQuestionInfoContent.setText(data.getQuizcontent());
        mTvQuestionInfoContent.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                int lineCount = mTvQuestionInfoContent.getLineCount();
                if (lineCount > 3) {
                    mTvQuestionInfoContent.setLines(3);
                    mBtnZhankaiAll.setVisibility(View.VISIBLE);
                } else {
                    mBtnZhankaiAll.setVisibility(View.GONE);
                }
                mBtnZhankaiAll.getViewTreeObserver().removeOnPreDrawListener(this);
                return false;
            }
        });
        mBtnZhankaiAll.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (flag) {
                    flag = false;
                    mTvQuestionInfoContent.setEllipsize(null); // 展开
                    mTvQuestionInfoContent.setSingleLine(flag);
                    mBtnZhankaiAll.setText("收起全部");
                } else {
                    flag = true;
                    mTvQuestionInfoContent.setEllipsize(TextUtils.TruncateAt.END); // 收缩
                    mTvQuestionInfoContent.setMaxLines(3);
                    mBtnZhankaiAll.setText("展开全部");
                }
            }
        });

       mRbQueestionCommentStar.setOnRatingChangeListener(new RatingBar.OnRatingChangeListener() {
            @Override
            public void onRatingChange(float ratingCount) {
                mScore = ratingCount;
                if (ratingCount > 0) {
                    mTvShowStar.setVisibility(View.VISIBLE);
                    mBtnConfrimComment.setVisibility(View.VISIBLE);
                } else {
                    mTvShowStar.setVisibility(View.GONE);
                    mBtnConfrimComment.setVisibility(View.GONE);
                }
                if (ratingCount == 1) {
                    mTvShowStar.setText("非常不满意");
                } else if (ratingCount == 2) {
                    mTvShowStar.setText("不满意");
                } else if (ratingCount == 3) {
                    mTvShowStar.setText("一般般");
                } else if (ratingCount == 4) {
                    mTvShowStar.setText("较满意");
                } else if (ratingCount == 5) {
                    mTvShowStar.setText("非常满意");
                }
            }
        });
        if (data.getQuestion() != null && data.getQuestion().size() > 0) {
            mAdapter.setNewData(data.getQuestion());
        } else {
            mAdapter.setEmptyView(mEmptyView.getEmptyView("暂无相关推荐问答"));
        }

        image = new UMImage(AskDetailActivity.this, data.getUserAccountFormMap().getUserHead());
        umWeb = new UMWeb("http://liebangapp.com/yindao/");
        umWeb.setTitle(data.getQuizcontent());//标题
        umWeb.setThumb(image);  //缩略图
        umWeb.setDescription(data.getAnswerContent());//描述

        if (data.getChargeState() == 0) {//限时免费
             if (data.getOrderStates()==3||AM.user().getLoginResultCache().getUserUid().equals(data.getUserAccountFormMap().getUserUid())){//已评论
                 mViewToComment.setVisibility(View.GONE);
             }else {
                 mViewToComment.setVisibility(View.VISIBLE);
             }
        } else if (data.getChargeState() == 1){//一元查看
            if (data.getOrderStates()!=3&&data.getIsBuy()==1){//已评论&&已购买
                mViewToComment.setVisibility(View.VISIBLE);
            }else {
                mViewToComment.setVisibility(View.GONE);
            }
            //判断是否隐藏一元查看按钮
            if (data.getIsBuy()==0){
                mIvShowLOOK.setVisibility(View.VISIBLE);
                mIvLookOne.setVisibility(View.VISIBLE);
                mTvAnswerContentComment.setVisibility(View.GONE);
                if (AM.user().getLoginResultCache().getUserUid().equals(data.getUserAccountFormMap().getUserUid())){
                    mIvShowLOOK.setVisibility(View.GONE);
                    mIvLookOne.setVisibility(View.GONE);
                    mTvAnswerContentComment.setVisibility(View.VISIBLE);
                }
            }else {
                mIvShowLOOK.setVisibility(View.GONE);
                mIvLookOne.setVisibility(View.GONE);
                mTvAnswerContentComment.setVisibility(View.VISIBLE);
            }
        }

    }

    @Override
    public void showRefusedQuestion(String s) {
        showMsg("忽略成功！");
        finish();
    }

    @Override
    public void showAnswerSuccess(String s) {
        showMsg("回答成功！");
        finish();
    }

    @Override
    public void showCommentSuccess(String s) {
        showMsg("评价成功！");
        mViewToComment.setVisibility(View.GONE);

    }


    @Override
    public void showOrderQuestionInfoError(String error) {
        showErrorMsg(error);
    }

    @Override
    public void showCommentDetailSuccess(String s) {
        showMsg("评价成功！");
        finish();
    }

    public void initAdapter() {
        mEmptyView = new EmptyView(mRvQuestioRecommend);
        mRvQuestioRecommend.setLayoutManager(new LinearLayoutManager(this));
        mRvQuestioRecommend.addItemDecoration(new DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(2));
        mAdapter = new QuestionRecommendAdapter();
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        mAdapter.bindToRecyclerView(mRvQuestioRecommend);
        mAdapter.setOnItemClickListener(this);
    }

    @SuppressLint("RestrictedApi")
    @OnClick({R.id.btn_question_info_ask, R.id.iv_show_LOOK, R.id.btn_confrim_answer,
            R.id.btn_confrim_comment, R.id.iv_question_info_head})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_question_info_ask:
                if (isExpert) {
                    mToolbar.getMenu().setGroupVisible(R.menu.menu_askinfo_hulue, false);
                    mToolbar.inflateMenu(R.menu.menu_save);
                    mViewExpertInfo.setVisibility(View.GONE);
                    mTypeQuestionValidateExpert.setVisibility(View.GONE);
                    mTypeQuestionAnswerExpert.setVisibility(View.VISIBLE);
                }

                Intent intentAsk = new Intent(this, AskActivity.class);
                intentAsk.putExtra("user_id", mData.getUserAccountFormMap().getUserUid());
                startActivity(intentAsk);
                break;
            case R.id.btn_confrim_answer:
                mPresenter.toAnswer(mAnswerId, mEdtAnswerContent.getText().toString(), mAnswerType);
                break;
            case R.id.btn_confrim_comment:
                mPresenter.toCommentInfo(mData.getChargeState(), mAnswerId, mScore);
                break;
            case R.id.iv_show_LOOK:
                Intent intent = new Intent(this, PayActivity.class);
                intent.putExtra("ask_prize", 1.00);
                intent.putExtra("questionId", mData.getId());
                intent.putExtra("order_type", OrderType.WEIGUAN.getIndex());
                startActivityForResult(intent, 3);
                break;
            case R.id.iv_question_info_head:
//                if(mData.getUserAccountFormMap().getDataPrivacyType()==0){
                Intent intents = new Intent(this, UserInfoActivity.class);
                intents.putExtra("is_view_my", false);
                intents.putExtra("visitorUid", mData.getUserAccountFormMap().getUserUid());
                startActivity(intents);
//                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            isPay = data.getBooleanExtra("is_ok", false);
            if (isPay) {
                mIvShowLOOK.setVisibility(View.GONE);
                mIvLookOne.setVisibility(View.GONE);
                mTvAnswerContentComment.setVisibility(View.VISIBLE);
                mViewToComment.setVisibility(View.VISIBLE);
            }
        } else if (requestCode == 23) {
            if (data==null) return;
            Friend friend = data.getParcelableExtra("three");

            if (friend==null) return;
            ShareQuestionBean questionBean = new ShareQuestionBean(mData.getQuizcontent(), friend.getUserUid(), "1", mData.getId());
            String json = JSONObject.toJSONString(questionBean);

            QuestionMessage questionMessage = QuestionMessage.obtain("",
                    "",
                    friend.getUserUid(),
                    json,
                    mData.getUserAccountFormMap().getUserUid(),
                    mData.getQuizcontent(),
                    "1",
                    mData.getId()

            );


            RongIM.getInstance().sendMessage(Message.obtain(questionBean.getShareUid(),
                    Conversation.ConversationType.PRIVATE, questionMessage), "sass", "sss",
                    new IRongCallback.ISendMessageCallback() {
                        @Override
                        public void onAttached(Message message) {

                        }

                        @Override
                        public void onSuccess(Message message) {
                            T.showShort("已发送！");
                            if (mShareDialog != null) {
                                mShareDialog.dismiss();
                            }
                            RongIM.getInstance().startConversation(AskDetailActivity.this, Conversation.ConversationType.PRIVATE, friend.getUserUid(), friend.getUserName());

                        }

                        @Override
                        public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                            T.showShort("onError" + errorCode.getMessage());
                            if (mShareDialog != null) {
                                mShareDialog.dismiss();
                            }
                        }
                    });
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_hulue:
                mPresenter.refusedQuestion(mAnswerId);
                break;
            case R.id.action_next:
                mPresenter.toAnswer(mAnswerId, mEdtAnswerContent.getText().toString(), mAnswerType);
                break;
            case R.id.action_share:
                BaseAnimatorSet mBasIn = new BounceTopEnter();
                mShareDialog.showAnim(mBasIn)
                        .show();
                mShareDialog.setWxCircleClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new ShareAction(AskDetailActivity.this)
                                .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                                .withMedia(umWeb)
                                .setCallback(shareListener)//回调监听器
                                .share();
                    }
                });
                mShareDialog.setWxClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new ShareAction(AskDetailActivity.this)
                                .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                                .withMedia(umWeb)
                                .setCallback(shareListener)//回调监听器
                                .share();
                    }
                });
                mShareDialog.setLBClickListener(this);
                break;
        }
        return false;
    }

    private UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            showLoading();
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            dismissLoading();
            T.showShort("分享成功！");
            if (mShareDialog != null) mShareDialog.dismiss();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            dismissLoading();
            T.showShort("分享失败！");
            if (mShareDialog != null) mShareDialog.dismiss();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            dismissLoading();
            T.showShort("分享取消！");

        }
    };

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.rgb_answer_1look) {
            mAnswerType = 1;
        } else {
            mAnswerType = 0;
        }
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }


    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, FriendsListActivity.class);
        intent.putExtra("is_select", true);
        startActivityForResult(intent, 23);


    }


}


